package edu.buaa.act.travel.m.page;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ListView;
import edu.buaa.act.travel.m.Constants;
import edu.buaa.act.travel.m.R;
import edu.buaa.act.travel.m.adapter.TripDetailAdapter;
import edu.buaa.act.travel.m.model.TripDetailModel;
import edu.buaa.act.travel.m.service.DataService;
import edu.buaa.act.travel.m.data.TripSimp;

public class TripDetailActivity extends BaseActivity {
	
	private ListView mListTrip;
	private TripDetailAdapter mTripDetailAdapter;
	
	private Handler mHandler = new Handler() {
		
		@Override
		public void handleMessage(final Message msg) {
			dismissDialog(DIALOG_WAIT);
			switch(msg.what) {
			case Constants.MESSAGE_GET_DATA_SUCCESS:
				setup((String) msg.obj);
				break;
			case Constants.MESSAGE_GET_DATA_FAIL:
				break;
			}
		}
	};
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.trip_list_activity);
        
        setupLeftPanelButton();
        setRightPanelButtonVisibility(View.GONE);
        
        final TripSimp trip = (TripSimp) getIntent().getSerializableExtra(Constants.EXTRA_TRIP);
        mListTrip = (ListView) findViewById(R.id.list_trip);
        getTripDetail();
	}
	
	private void setup(final String result) {
		mTripDetailAdapter = new TripDetailAdapter(this, new TripDetailModel(result).getTripDetails());
		mListTrip.setAdapter(mTripDetailAdapter);
		
		setRightPanelButtonVisibility(View.VISIBLE);
		setupRightPanelButton(R.string.title_run, new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				goToRun(result);
			}
		});
	}
	
	private void getTripDetail() {
		showDialog(DIALOG_WAIT);
		DataService.get(Constants.URL_GET_TRIP, 
				mHandler, 
				Constants.MESSAGE_GET_DATA_SUCCESS, 
				Constants.MESSAGE_GET_DATA_FAIL);
	}

	private void goToRun(final String result) {
		final Intent intent = new Intent(this, RunActivity.class);
		intent.putExtra(Constants.EXTRA_TRIP_DETAILS, result);
		startActivity(intent);
	}
}
